/*
 * Copyright 2021 TiKV Project Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.webank.tikv.common;

import com.google.common.collect.ImmutableSet;
import com.webank.tikv.exception.GrpcException;
import com.webank.tikv.operation.ErrorHandler;
import com.webank.tikv.util.BackOffer;
import io.grpc.Status;

import java.util.concurrent.Callable;

public class RetryPolicy<RespT> {

    private final BackOffer backOffer;
    private final ErrorHandler<RespT> handler;

    private final ImmutableSet<Status.Code> unrecoverableStatus = ImmutableSet.of(
        Status.Code.ALREADY_EXISTS, Status.Code.PERMISSION_DENIED, Status.Code.INVALID_ARGUMENT,
        Status.Code.NOT_FOUND, Status.Code.UNIMPLEMENTED, Status.Code.OUT_OF_RANGE,
        Status.Code.UNAUTHENTICATED, Status.Code.CANCELLED);

    public RetryPolicy(BackOffer backOffer, ErrorHandler<RespT> handler) {
        this.backOffer = backOffer;
        this.handler = handler;
    }

    private void rethrowNotRecoverableException(Exception e) {
        Status status = Status.fromThrowable(e);
        if (unrecoverableStatus.contains(status.getCode())) {
            throw new GrpcException(e);
        }
    }

    public RespT callWithRetry(Callable<RespT> proc) {
        while (true) {
            RespT result = null;
            try {
                result = proc.call();
            } catch (Exception e) {
                rethrowNotRecoverableException(e);
                if (handler.handleRequestError(backOffer, e)) {
                    continue;
                }
            }
            return result;
        }
    }

}
